import { ref, reactive } from "@vue/composition-api";
import { Notification, Message } from "fawkes-lib";
import {
  uefileUpload,
  mergeUefile,
  getMergeProgress,
  checkUefileExistence,
} from "../apis/index";
import { unzipUefile, getUnzipUefileProgress } from "../apis/ueproject";
export default function useUefileUpload() {
  const uploading = ref(false); // 上传状态
  const progress = ref(0); // 上传进度
  const mergeProgress = reactive({
    status: true,
    data: null,
  });
  const unzipProgress = reactive({
    status: true,
    data: null,
  });
  const deployFlag = ref(true);

  /**
   * @description: 上传分片
   * @param {*} file
   * @param {*} cb
   */
  const uploadFileChunks = async (file, cb) => {
    const chunkSize = 10 * 1024 * 1024; // 每个分片的大小
    const chunks = Math.ceil(file.size / chunkSize); // 总分片数
    let currentChunk = 0;

    const uploadChunk = async (chunk) => {
      const formData = new FormData();
      formData.append("file", chunk);
      formData.append("name", file.name);
      formData.append("chunk", currentChunk + 1); // 分片序号，从1开始
      formData.append("chunks", chunks); // 总分片数

      try {
        const response = await uefileUpload(formData);
        if (response.status) {
          // 分片上传成功，更新进度
          currentChunk++;
          progress.value = Math.ceil((currentChunk / chunks) * 100);

          // 上传下一分片
          if (currentChunk < chunks) {
            const nextChunkStart = currentChunk * chunkSize;
            const nextChunkEnd = Math.min(
              nextChunkStart + chunkSize,
              file.size
            );
            const nextChunk = file.slice(nextChunkStart, nextChunkEnd);
            uploadChunk(nextChunk);
          } else {
            // 所有分片上传完毕
            uploading.value = false;
            Notification({
              title: "提醒",
              message: "正在合并分片...",
              type: "info",
            });
            // 发起合并
            mergeUefile({
              name: file.name,
              chunks,
            }).then((res) => {
              const taskId = res.data;
              const timer = setInterval(async () => {
                const progressResponse = await getMergeProgress(taskId);
                console.log("progressResponse==", progressResponse);
                mergeProgress.status = progressResponse.data.status;
                mergeProgress.data = progressResponse.data.data;
                if (progressResponse.data.status) {
                  clearInterval(timer);
                  // 合并完成进度归0
                  progress.value = 0;
                  cb({
                    originalFilename:
                      progressResponse.data.data.originalFilename,
                    path: progressResponse.data.data.path,
                  });
                }
              }, 2000);
            });
          }
        } else {
          console.error("分片上传失败", response.data);
          uploading.value = false;
        }
      } catch (error) {
        console.error("上传过程中出错", error);
        uploading.value = false;
      }
    };

    // 查询是否存在同名大文件
    checkUefileExistence({
      name: file.name,
    })
      .then((res) => {
        // 检测到同名大文件res = undefind，未检测到res为一个对象
        if (!res.status) {
          Notification({
            title: "提醒",
            message: res.message,
            type: "info",
          });
          return;
        }
        // 开始上传第一块分片
        uploading.value = true; // 开始上传
        const firstChunk = file.slice(0, chunkSize);
        uploadChunk(firstChunk);
      })
      .catch((err) => {
        console.log(err);
      });
  };
  /**
   * @description: 部署UE工程
   * @return {*}
   */
  const deployUefile = (data) => {
    deployFlag.value = false;
    Notification({
      title: "提醒",
      message: "正在处理ue文件...",
      type: "info",
    });
    let unzipTimer = null;
    unzipUefile(data).then((res) => {
      const taskId = res.data;
      unzipTimer = setInterval(async () => {
        const progressResponse = await getUnzipUefileProgress(taskId);
        unzipProgress.status = progressResponse.data.status;
        unzipProgress.data = progressResponse.data.data;
        if (progressResponse.data.status) {
          clearInterval(unzipTimer);
          unzipTimer = null;
          deployFlag.value = true;
          Message({
            type: "success",
            message: "部署完成！",
          });
        }
      }, 2000);
    });
  };
  return {
    uploading,
    progress,
    mergeProgress,
    unzipProgress,
    uploadFileChunks,
    deployUefile,
    deployFlag,
  };
}
